import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Welcome from '../components/Welcome.vue'
import Dept from '../components/Dept.vue'
import Emp from '../components/Emp.vue'
import A from '../components/A.vue'
import AA from '../components/AA.vue'
import Error from '../components/Error.vue'


Vue.use(VueRouter)

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  //路由匹配不到的重定向配置
  {
    path: '*',
    redirect: "/error"
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
  {
    path: '/welcome',
    name: 'welcome',
    component: Welcome,
    //一级路由时默认自动跳转指定的二级路由页面
    redirect: "/emp",
    children: [{
      path: "/dept",
      name: "dept",
      component: Dept,
    },
    {
      path: "/emp",
      name: "emp",
      component: Emp,
    }],
  },
  /* {
    path: '/dept',
    name: 'dept',
    component: Dept,
  },
  {
    path: '/emp',
    name: 'emp',
    component: Emp,
  }, */
  {
    path: '/a',
    name: 'a',
    component: A,
    children: [{
      path: "/aa",
      name: "aa",
      component: AA,
    }],
  },
  {
    path: '/error',
    name: 'error',
    component: Error,
  },
]


const router = new VueRouter({
  routes,
  mode: "hash"  //hash:默认’hash’值，但是hash看起来就像无意义的字符排列，不太好看也不符合我们一般的网址浏览习惯。
  //mode:"history" //hash url 跳转histroy:当你使用 history 模式时，URL 就像正常的 url，例如 http://localhost:8080/hi，也好看！
})


//路由守卫应该写到const router 后面
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const store = window.sessionStorage.getItem('storeData')
  console.log(store)
  if (store == null) {
    return next('/login');
  }
  next();
})

export default router